package com.qf.service.Impl;

import com.qf.dao.Impl.MusicDaoImpl;
import com.qf.dao.MusicDao;
import com.qf.pojo.Music;
import com.qf.service.MusicService;
import com.qf.util.DBUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class MusicServiceImpl implements MusicService {
    private MusicDao musicDao = new MusicDaoImpl();
    @Override
    public List<Music> findAll() {
        //由于是查询操作，没有业务逻辑，我们直接调用Dao层
        return musicDao.findAll();
    }

    @Override
    public List<Music> findByName(String musicName) {
        return musicDao.findByName(musicName);
    }

    @Override
    public Music findById(String musicId) {
        return musicDao.findById(musicId);
    }

    @Override
    public Music nextSong(String musicId) {
        List<Music> musicList = musicDao.findAll();
        Integer currentMusic = null;
        if (musicList != null && musicList.size()>0){
            for (int i = 0; i < musicList.size(); i++) {
                if (musicList.get(i).getMusicId().toString().equals(musicId)) {
                    currentMusic = i;
                    break;
                }
            }
        }
        int nextSongIndex = currentMusic == musicList.size() - 1 ? 0 : currentMusic + 1;

        return musicList.get(nextSongIndex);
    }

    @Override
    public Music lastSong(String musicId) {
        List<Music> musicList = musicDao.findAll();
        Integer currentMusic = null;
        if (musicList != null && musicList.size()>0){
            for (int i = 0; i < musicList.size(); i++) {
                if (musicList.get(i).getMusicId().toString().equals(musicId)) {
                    currentMusic = i;
                    break;
                }
            }
        }
        int lastSongIndex = currentMusic == 0 ? musicList.size()-1 : currentMusic - 1;

        return musicList.get(lastSongIndex);
    }

    @Override
    public List<Music> findByPage(String page, String limit) {
        return musicDao.findByPage(page,limit);
    }

    @Override
    public Long queryTotalCount() {
        return musicDao.queryTotalCount();
    }

    @Override
    public void add(Music music) {
        DBUtils.begin();
        try {
            musicDao.add(music);
        } catch (Exception e) {
            e.printStackTrace();
            DBUtils.rollback();
        } finally {
            DBUtils.commit();
        }
    }
}
